<?php

/**
 * TomatoCMS
 * 
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@tomatocms.com so we can send you a copy immediately.
 * 
 * @copyright	Copyright (c) 2009-2010 TIG Corporation (http://www.tig.vn)
 * @license		http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @version 	$Id: ArticleController.php 5462 2010-09-20 04:45:41Z huuphuoc $
 * @since		2.0.0
 */
class News_ArticleController extends Zend_Controller_Action {

    /**
     * Init controller
     *
     * @return void
     */
    public function init() {
        /**
         * Register hooks
         * @since 2.0.2
         */
//            if (Zend_Registry::isRegistered('test')) {
//                var_dump(Zend_Registry::get('test'));
//            }else{
//                Zend_Registry::set('test', 'list');
//            }
//		Tomato_Hook_Registry::getInstance()->register('News_Article_Add_ShowSidebar', array(
//			new Tag_Hooks_Tagger_Hook(),
//			'show',
//			array('article_id', 'news_article_details', 'news_tag_article')
//		));
//		Tomato_Hook_Registry::getInstance()->register('News_Article_Edit_ShowSidebar', array(
//			new Tag_Hooks_Tagger_Hook(),
//			'show',
//			array('article_id', 'news_article_details', 'news_tag_article')
//		));
//		Tomato_Hook_Registry::getInstance()->register(
//			'News_Article_Add_Success',
//			'Tag_Hooks_Tagger_Hook::add'
//		);
//		Tomato_Hook_Registry::getInstance()->register(
//			'News_Article_Edit_Success',
//			'Tag_Hooks_Tagger_Hook::add'
//		);
    }

    /* ========== Frontend actions ========================================== */

    /**
     * List articles in given category
     *
     * @return void
     */
    public function categoryAction() {
        $request = $this->getRequest();
        $categoryId = $request->getParam('category_id');
        $pageIndex = $request->getParam('page_index', 1);
        $perPage = 2;
        $offset = ($pageIndex - 1) * $perPage;

        $categoryModel = Rabbit_Model_Factory::getInstance()->setModule('category')->getCategoryModel();
        $category = $categoryModel->getById($categoryId);

        if (null == $category) {
            throw new Tomato_Exception_NotFound();
        }

        /**
         * Add RSS link
         */
//        $this->view->headLink(array(
//            'rel' => 'alternate',
//            'type' => 'application/rss+xml',
//            'title' => 'RSS',
//            'href' => $this->view->url($category->getProperties(), 'news_rss_category'),
//        ));

        /**
         * Add meta keyword tag
         */
        if ($category->meta_keywords) {
            $keywords = strip_tags($category->meta_keywords);
            $this->view->headMeta()->setName('keywords', $keywords);
        }

        /**
         * Add meta description tag
         */
        if ($category->meta_description){
            $description = strip_tags($category->meta_description);
            $this->view->headMeta()->setName('description', $description);
        }
        /**
         * Add title
         */
        if ($category->meta_title) {
            $this->view->headTitle($category->meta_title, 'SET');
        } else {
            $this->view->headTitle($category->name, 'SET');
        }
        $articleModel = Rabbit_Model_Factory::getInstance()->setModule('news')->getArticleModel();
        $articles = $articleModel->getByCategory($categoryId, $offset, $perPage);
        $numArticles = $articleModel->count(array('status' => 'actived', 'category_id' => $categoryId));

        /**
         * Paginator
         */
        $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($articles, $numArticles));
        $paginator->setCurrentPageNumber($pageIndex);
        $paginator->setItemCountPerPage($perPage);

        $this->view->assign('articles', $articles);
        $this->view->assign('category', $category);
        $this->view->assign('pageIndex', $pageIndex);
        $this->view->assign('paginator', $paginator);
        $properties = $category->getProperties();
        $properties['category_id'] = $properties['id'];
        $this->view->assign('paginatorOptions', array(
            'path' => $this->view->url($properties, 'news_article_category'),
            'itemLink' => 'page-%d',
        ));
    }

    /**
     * View article details
     *
     * @return void
     */
    public function detailsAction() {
        try {
            $request = $this->getRequest();
            $articleId = $request->getParam('id');
            $categoryId = $request->getParam('category_id');
//        $preview = $request->getParam('preview');
//        $preview = ($preview == 'true') ? true : false;

            /**
             * If user are going to preview article
             * @since 2.0.4
             */
//        if ($preview) {
//            $revisionId = $request->getParam('revision');
//            if ($revisionId) {
//                $this->_forward('preview', 'article', 'news', array('revision_id' => $revisionId));
//                return;
//            }
//        }


            $articleModel = Rabbit_Model_Factory::getInstance()->setModule('news')->getArticleModel();
            $article = $articleModel->getById($articleId);

            if (null == $article || ($article->status != 'actived' )) {//&& !$preview
                throw new Exception('Not found article with Id of ' . $articleId);
            }

            /**
             * Add meta keywords
             */
            if ($article->meta_keywords) {
                $this->view->headMeta($article->meta_keywords, "keywords", 'name', array(), 'SET');
            }
            /**
             * Add meta description tag
             */
            if ($article->meta_description) {
                $description = strip_tags($article->meta_description);
                $this->view->headMeta()->setName('description', $description);
            }
            /**
             * Add title
             */
            if ($article->meta_title) {
                $this->view->headTitle($article->meta_title, 'SET');
            } else {
                $this->view->headTitle($article->title, 'SET');
            }

            /**
             * Format content
             */
            //$article->content = Tomato_Hook_Registry::getInstance()->executeFilter('News_Article_Details_FormatContent', $article->content);

            /**
             * Add activate date
             * @since 2.0.4
             */
            if (null == $article->activate_date) {
                $article->activate_date = $article->created_date;
            }

            if (null == $categoryId) {
                $categoryId = $article->category_id;
            }

            $categoryModel = Rabbit_Model_Factory::getInstance()->setModule('category')->getCategoryModel();
            $category = $categoryModel->getById($categoryId);

            /**
             * Increase article views
             */
            if ($article->status != 'drafted') {//!$preview &&
                $cookieName = '__rabbit_news_details_numviews';
                $viewed = false;
                if (!isset($_COOKIE[$cookieName])) {
                    setcookie($cookieName, $articleId, time() + 3600);
                } else {
                    if (strpos($_COOKIE[$cookieName], $articleId) === false) {
                        $cookie = $_COOKIE[$cookieName] . ',' . $articleId;
                        setcookie($cookieName, $cookie);
                    } else {
                        $viewed = true;
                    }
                }
                if (!$viewed) {
                    $articleModel->increaseViews($articleId);
                }
            }

            $this->view->assign('article', $article);
            $this->view->assign('category', $category);
        } catch (Exception $ex) {
            echo $ex->getMessage();
        };
    }

    /**
     * Search articles by keyword
     *
     * @since 2.0.2
     * @return void
     */
    public function searchAction() {
        $request = $this->getRequest();
        $keyword = $request->getParam('q');
        $pageIndex = $request->getParam('page_index', 1);

        $purifier = new HTMLPurifier();
        $keyword = $purifier->purify($keyword);

        $perPage = 10;
        $offset = ($pageIndex - 1) * $perPage;

        if (null == $keyword) {
            return;
        }
        $conn = Tomato_Db_Connection::factory()->getSlaveConnection();
        $articleModel = Tomato_Model_Factory::getInstance()->setModule('news')->getArticleDao();
        $articleModel->setDbConnection($conn);

        $exp = array(
            'keyword' => $keyword,
            'status' => 'active',
        );
        $articles = $articleModel->find($offset, $perPage, $exp);
        $numArticles = $articleModel->count($exp);

        /**
         * Paginator
         */
        $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($articles, $numArticles));
        $paginator->setCurrentPageNumber($pageIndex);
        $paginator->setItemCountPerPage($perPage);

        $from = ($numArticles > 0) ? $offset + 1 : 0;
        $to = 0;
        if ($numArticles > 0) {
            $to = ($from + $perPage <= $numArticles) ? ($from + $perPage - 1) : $numArticles;
        }

        $this->view->assign('keyword', $keyword);
        $this->view->assign('pageIndex', $pageIndex);
        $this->view->assign('articles', $articles);
        $this->view->assign('numArticles', $numArticles);
        $this->view->assign('paginator', $paginator);
        $this->view->assign('paginatorOptions', array(
            'path' => $this->view->url(array(), 'news_article_search'),
            'itemLink' => '?q=' . $keyword . '&page_index=%d',
        ));
        $this->view->assign('from', $from);
        $this->view->assign('to', $to);
    }

    /**
     * Suggest list of articles containing keyword
     *
     * @since 2.0.3
     * @return void
     */
    public function suggestAction() {
        $this->_helper->getHelper('viewRenderer')->setNoRender();
        $this->_helper->getHelper('layout')->disableLayout();

        $request = $this->getRequest();
        $limit = $request->getParam('limit');
        $keyword = $request->getParam('q');
        $keyword = strip_tags($keyword);

        $exp = array(
            'keyword' => $keyword,
            'status' => 'active',
        );
        $conn = Tomato_Db_Connection::factory()->getSlaveConnection();
        $articleModel = Tomato_Model_Factory::getInstance()->setModule('news')->getArticleDao();
        $articleModel->setDbConnection($conn);
        $articles = $articleModel->find(0, $limit, $exp);

        $response = null;
        foreach ($articles as $article) {
            $response .= $article->title . '|' . $article->article_id . '|' . $article->image_square . "\n";
        }
        $this->_response->setBody($response);
    }

    /**
     * Update Rating
     * @author TrongHM 
     */
    public function rateAction() {
        $request = $this->getRequest();
        $this->_helper->getHelper('viewRenderer')->setNoRender();
        $this->_helper->getHelper('layout')->disableLayout();
        if ($request->isPost()) {
            $rate = $request->getPost('rate');
            $id = $request->getPost('idBox');
            $articleModel = Rabbit_Model_Factory::getInstance()->setModule('news')->getArticleModel();


            if ($articleModel->rate($id, $rate)) {
                $this->_response->setBody('RESULT_OK');
            } else {
                $this->_response->setBody('RESULT_FAILED');
            }
        }
    }

    /* ========== Backend actions =========================================== */

    /**
     * Activate or deactivate article
     *
     * @return void
     */
    public function activateAction() {
        $request = $this->getRequest();
        $this->_helper->getHelper('viewRenderer')->setNoRender();
        $this->_helper->getHelper('layout')->disableLayout();

        if ($request->isPost()) {
            $status = ($request->getPost('status') == 'active') ? 'inactive' : 'active';
            $id = $request->getPost('id');
            $ids = array();
            if (is_numeric($id)) {
                $ids[] = $id;
            } else {
                $ids = Zend_Json::decode($id);
            }

            $conn = Tomato_Db_Connection::factory()->getMasterConnection();
            $articleModel = Tomato_Model_Factory::getInstance()->setModule('news')->getArticleDao();
            $articleModel->setDbConnection($conn);
            foreach ($ids as $articleId) {
                $articleModel->updateStatus($articleId, $status);
            }

            $this->getResponse()->setBody($status);
        }
    }

    /**
     * Add new article
     *
     * @return void
     */
    public function addAction() {
        $request = $this->getRequest();
        /**
         * Changed by TrongHM
         */
        $articleModel = Rabbit_Model_Factory::getInstance()->setModule('news')->getArticleModel();
        //$categoryModel = Rabbit_Model_Factory::getInstance()->setModule('category')->getCategoryModel();
        //$this->view->assign('categories', $categories);
        //$revisionDao = Tomato_Model_Factory::getInstance()->setModule('news')->getRevisionDao();
        //$revisionDao->setDbConnection($conn);


        /**
         * @since 2.0.8
         */
        $sourceId = $request->getParam('source_id');
        $sourceArticle = (null == $sourceId) ? null : $articleModel->getById($sourceId);
        $this->view->assign('translatableData', (null == $sourceArticle) ? array() : $sourceArticle->getProperties());
        $this->view->assign('sourceArticle', $sourceArticle);
        $this->view->assign('lang', $request->getParam('lang'));
        if ($request->isPost()) {
            $user = Zend_Auth::getInstance()->getIdentity();
            $articleImages = $request->getPost('articleImages');
            $imageUrls = Zend_Json::decode(stripslashes($articleImages));

//			$preview 	  = $request->getPost('preview');
//			$preview 	  = ($preview == 'true') ? true : false;
//			$imageUrls 	  = Zend_Json::decode(stripslashes($articleImage));
//			$articleIcons = "";
//			if (count($icons) == 1 ) {
//				$articleIcons = '{"' . $icons[0] . '"}';
//			}
//			if (count($icons) == 2 ) {
//				$articleIcons = '{"' . $icons[0] . '","' . $icons[1] . '"}';
//			}
            $article = new News_Models_Entities_Article(array(
                        'category_id' => $request->getPost('category_id'),
                        'title' => strip_tags($request->getPost('title')),
                        'slug' => $request->getPost('slug'),
                        'summary' => $request->getPost('summary'),
                        'content' => $request->getPost('content'),
                        'featured' => $request->getPost('featured', 0),
                        'allow_comment' => $request->getPost('allow_comment', 0),
                        'created_date' => date('Y-m-d H:i:s'),
                        'created_user_id' => $user->id,
                        'created_user_name' => $user->username,
                        'author' => strip_tags($request->getPost('author')),
                        //'icons' 			=> $articleIcons,
                        //'sticky' 			=> false,
                        'status' => $request->getPost('status'),
                        /**
                         * @since 2.0.8
                         */
                        'language' => $request->getPost('language'),
                        'meta_title' => strip_tags($request->getPost('meta_title')),
                        'meta_description' => strip_tags($request->getPost('meta_description')),
                        'meta_keywords' => strip_tags($request->getPost('meta_keywords')),
                    ));
//			if ($preview) {
//				$article->status = 'draft';
//			}
//			if ($sticky == 1) {
//				$article->sticky = true;
//			}
            if (null != $imageUrls) {
                $article->image_original = $imageUrls['original'];
                $article->image_square = $imageUrls['square'];
                $article->image_thumbnail = $imageUrls['thumbnail'];
                $article->image_small = $imageUrls['small'];
                $article->image_crop = $imageUrls['crop'];
                $article->image_medium = $imageUrls['medium'];
                $article->image_large = $imageUrls['large'];
            }
            $id = $articleModel->add($article);
            if ($id) {
                /**
                 * Add translation relation
                 * @since 2.0.8
                 */
                $source = Zend_Json::decode($request->getPost('sourceItem', '{"id": "", "language": ""}'));

                $translationModel = Rabbit_Model_Factory::getInstance()->setModule('core')->getTranslationModel();
                $translationModel->add(new Core_Models_Entities_Translation(array(
                            'item_id' => $id,
                            'item_class' => get_class($article),
                            'source_item_id' => ('' == $source['id']) ? $id : $source['id'],
                            'language' => $article->language,
                            'source_language' => ('' == $source['language']) ? null : $source['language'],
                        )));

                /**
                  //				 * Save draft and preview article
                  //				 * @since 2.0.4
                  // */
//				if ($preview) {
//					$this->_helper->getHelper('viewRenderer')->setNoRender();
//					$this->_helper->getHelper('layout')->disableLayout();
//					$article->article_id = $id;
//					$response = array(
//						'article_id' 	   => $id,
//						'article_url' 	   => $this->view->serverUrl() . $this->view->url($article->getProperties(), 'news_article_details') . '?preview=true',
//						'article_edit_url' => $this->view->serverUrl() . $this->view->url($article->getProperties(), 'news_article_edit'),
//					);
//					$this->_response->setBody(Zend_Json::encode($response));
//				} else {
//					$articleModel->addToCategory($id, $categoryId);
//					if ($articleCats) {
//						for ($i = 0; $i < count($articleCats); $i++) {
//							if ($articleCats[$i] != $categoryId) {
//								$articleModel->addToCategory($id, $articleCats[$i]);
//							}
//						}
//					}
//
//					if ($request->getPost('hotArticle') == 1) {
//						$articleModel->addHotArticle($id);
//					}
//
//					/**
//					 * Add new revistion
//					 * @since 2.0.4
//					 */
//					$revisionDao->add(new News_Models_Revision(array(
//						'article_id' 		=> $id,
//						'category_id' 		=> $categoryId,
//						'title' 			=> $title,
//						'sub_title' 		=> $subTitle,
//						'slug' 				=> $slug,
//						'description' 		=> $description,
//						'content' 			=> $content,
//						'created_date' 		=> date('Y-m-d H:i:s'),
//						'created_user_id' 	=> $user->user_id,
//						'created_user_name' => $user->user_name,
//						'author' 			=> $author,
//						'icons' 			=> $articleIcons,
//					)));
//
//					/**
//					 * Execute hooks
//					 * @since 2.0.2
//					 */
//					Tomato_Hook_Registry::getInstance()->executeAction('News_Article_Add_Success', $id);
//
                $this->_helper->getHelper('FlashMessenger')
                        ->addMessage('success:' . $this->view->translate('article_add_success'));
                //$this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'news_article_add'));
                $this->_redirect($this->view->serverUrl() . $this->view->url(array('id' => $id), 'news_article_edit')); //. '/' . $article->language . '/');
            } else {
                $this->_helper->getHelper('FlashMessenger')
                        ->addMessage('error:' . $this->view->translator('article_add_error'));
            }
        }
    }

    /**
     * Delete article
     *
     * @return void
     */
    public function deleteAction() {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender();

        $request = $this->getRequest();
        $result = 'RESULT_ERROR';
        if ($request->isPost()) {
            $id = $request->getPost('id');
            $ids = array();
            if (is_numeric($id)) {
                $ids[] = $id;
            } else {
                $ids = Zend_Json::decode($id);
            }

            $articleModel = Rabbit_Model_Factory::getInstance()->setModule('news')->getArticleModel();

            foreach ($ids as $articleId) {
                $article = $articleModel->getById($articleId);
                if ($article != null) {
                    if ('deleted' == $article->status) {
                        if ($articleModel->delete($articleId))
                            $result = 'RESULT_OK';

                        /**
                         * @since 2.0.8
                         */
//                        $translationDao = Tomato_Model_Factory::getInstance()->setModule('core')->getTranslationDao();
//                        $translationDao->setDbConnection($conn);
//                        $translationDao->delete($articleId, get_class($article));
                    } else {
                        if ($articleModel->updateStatus($articleId, 'deleted'))
                            $result = 'RESULT_OK';;
                    }
                }
            }
        }
        $this->getResponse()->setBody($result);
    }

    /**
     * Edit article
     *
     * @return void
     */
    public function editAction() {
        $request = $this->getRequest();
        $articleId = $request->getParam('id');
        $articleModel = Rabbit_Model_Factory::getInstance()->setModule('news')->getArticleModel();
//        $categoryModel = Rabbit_Model_Factory::getInstance()->setModule('category')->getCategoryModel();
//        $categories = $categoryModel->getTree();
//        $this->view->assign('categories', $categories);
        //$revisionDao = Tomato_Model_Factory::getInstance()->setModule('news')->getRevisionDao();
        //$revisionDao->setDbConnection($conn);

        $article = $articleModel->getById($articleId);
        if (null == $article) {
            throw new Exception('Not found article with id of ' . $articleId);
        }

        /**
         * @since 2.0.8
         */
        $sourceArticle = $articleModel->getSource($article);
        //$categories = $articleModel->getCategoryIds($articleId);
        //$isHot = $articleModel->isHot($articleId);

        $this->view->assign('article', $article);
        $this->view->assign('articleImages', Zend_Json::encode(array(
                    'original' => $article->image_original,
                    'square' => $article->image_square,
                    'thumbnail' => $article->image_thumbnail,
                    'small' => $article->image_small,
                    'crop' => $article->image_crop,
                    'medium' => $article->image_medium,
                    'large' => $article->image_large,
                )));
//        $this->view->assign('categories', $categories);
//        $this->view->assign('hotArticle', $isHot);
        $this->view->assign('sourceArticle', $sourceArticle);

        if ($request->isPost()) {
            $user = Zend_Auth::getInstance()->getIdentity();
            $articleImages = $request->getPost('articleImages');
            $imageUrls = Zend_Json::decode(stripslashes($articleImages));

            $params = array(
                'id' => $article->id,
                'category_id' => $request->getPost('category_id'),
                'title' => strip_tags($request->getPost('title')),
                'slug' => $request->getPost('slug'),
                'summary' => $request->getPost('summary'),
                'content' => $request->getPost('content'),
                'featured' => $request->getPost('featured'),
                'allow_comment' => $request->getPost('allow_comment'),
                'updated_date' => date('Y-m-d H:i:s'),
                'updated_user_id' => $user->id,
                'updated_user_name' => $user->username,
                'author' => strip_tags($request->getPost('author')),
                //'icons' 			=> $articleIcons,
                //'sticky' 			=> false,
                'status' => $request->getPost('status'),
                /**
                 * @since 2.0.8
                 */
                'language' => $request->getPost('language'),
                'meta_title' => strip_tags($request->getPost('meta_title')),
                'meta_description' => strip_tags($request->getPost('meta_description')),
                'meta_keywords' => strip_tags($request->getPost('meta_keywords')),
            );

            if (null != $imageUrls) {
                $params['image_original'] = $imageUrls['original'];
                $params['image_square'] = $imageUrls['square'];
                $params['image_thumbnail'] = $imageUrls['thumbnail'];
                $params['image_small'] = $imageUrls['small'];
                $params['image_crop'] = $imageUrls['crop'];
                $params['image_medium'] = $imageUrls['medium'];
                $params['image_large'] = $imageUrls['large'];
            }
            //$sticky = $request->getPost('stickyCategory');
//            $preview = $request->getPost('preview');
//            $preview = ($preview == 'true') ? true : false;
//            $articleIcons = "";
//            if (count($icons) == 1) {
//                $articleIcons = '{"' . $icons[0] . '"}';
//            }
//            if (count($icons) == 2) {
//                $articleIcons = '{"' . $icons[0] . '","' . $icons[1] . '"}';
//            }

            if ($articleModel->edit($params)) {
                $this->_helper->getHelper('FlashMessenger')
                        ->addMessage('success:' . $this->view->translate('article_edit_success'));
            } else {
                $this->_helper->getHelper('FlashMessenger')
                        ->addMessage('error:' . $this->view->translate('article_edit_error'));
            }
            $this->_redirect($this->view->serverUrl() . $this->view->url(array('id' => $articleId), 'news_article_edit'));

            /**
             * Update translation relation
             * @since 2.0.8
             */
//            $source = Zend_Json::decode($request->getPost('sourceItem', '{"id": "", "language": ""}'));
//            $translationDao = Tomato_Model_Factory::getInstance()->setModule('core')->getTranslationDao();
//            $translationDao->setDbConnection($conn);
//            $translationDao->update(new Core_Models_Translation(array(
//                        'item_id' => $article->article_id,
//                        'item_class' => get_class($article),
//                        'source_item_id' => ('' == $source['id']) ? $article->article_id : $source['id'],
//                        'language' => $article->language,
//                        'source_language' => ('' == $source['language']) ? null : $source['language'],
//                    )));
//
//            if ($preview) {
//                $this->_helper->getHelper('viewRenderer')->setNoRender();
//                $this->_helper->getHelper('layout')->disableLayout();
//                $response = array(
//                    'article_id' => $article->article_id,
//                    'article_url' => $this->view->serverUrl() . $this->view->url($article->getProperties(), 'news_article_details') . '?preview=true',
//                );
//                $this->_response->setBody(Zend_Json::encode($response));
//            } else {
//                $articleModel->addToCategory($articleId, $categoryId, true);
//                if ($articleCats) {
//                    for ($i = 0; $i < count($articleCats); $i++) {
//                        if ($articleCats[$i] != $categoryId) {
//                            $articleModel->addToCategory($articleId, $articleCats[$i]);
//                        }
//                    }
//                }
//                if ($request->getPost('hotArticle') == 1) {
//                    $articleModel->addHotArticle($articleId, true);
//                }
//
//                /**
//                 * Add new revistion
//                 * @since 2.0.4
//                 */
//                $revisionDao->add(new News_Models_Revision(array(
//                            'article_id' => $articleId,
//                            'category_id' => $categoryId,
//                            'title' => $article->title,
//                            'sub_title' => $article->sub_title,
//                            'slug' => $article->slug,
//                            'description' => $article->description,
//                            'content' => $article->content,
//                            'created_date' => date('Y-m-d H:i:s'),
//                            'created_user_id' => $user->user_id,
//                            'created_user_name' => $user->user_name,
//                            'author' => $article->author,
//                            'icons' => $articleIcons,
//                        )));
//
//                /**
//                 * Execute hooks
//                 * @since 2.0.2
//                 */
//                Tomato_Hook_Registry::getInstance()->executeAction('News_Article_Edit_Success', $articleId);
        }
    }

    /**
     * Empty the trash
     *
     * @return void
     * @since 2.0.7
     */
    public function emptytrashAction() {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender();

        $request = $this->getRequest();
        if ($request->isPost()) {
            $conn = Tomato_Db_Connection::factory()->getMasterConnection();
            $articleModel = Tomato_Model_Factory::getInstance()->setModule('news')->getArticleDao();
            $articleModel->setDbConnection($conn);
            $articleModel->delete();

            $this->getResponse()->setBody('RESULT_OK');
        }
    }

    /**
     * Manage hot articles
     *
     * @return void
     */
    public function hotAction() {
        $request = $this->getRequest();
        $limit = 20;

        $conn = Tomato_Db_Connection::factory()->getMasterConnection();
        $articleModel = Tomato_Model_Factory::getInstance()->setModule('news')->getArticleDao();
        $articleModel->setDbConnection($conn);

        /**
         * @since 2.0.8
         */
        $lang = $request->getParam('lang', Tomato_Config::getConfig()->web->lang);
        $articleModel->setLang($lang);

        if ($request->isPost()) {
            $this->_helper->getHelper('layout')->disableLayout();
            $this->_helper->getHelper('viewRenderer')->setNoRender();
            $articleIds = $request->getPost('articleRow');
            $response = 'RESULT_ERROR';

            /**
             * Update ordering all hot articles
             */
            $articleModel->updateHotOrder(1000);

            if (is_array($articleIds)) {
                for ($i = 0; $i < count($articleIds); $i++) {
                    $articleModel->updateHotOrder($i + 1, $articleIds[$i]);
                }
                $response = 'RESULT_OK';
            }
            $this->getResponse()->setBody($response);
            return;
        }

        $articles = $articleModel->getHotArticles($limit);
        $this->view->assign('articles', $articles);
        $this->view->assign('numArticles', $articles->count());
    }

    /**
     * List articles
     *
     * @return void
     */
    public function listAction() {
        $articleModel = Rabbit_Model_Factory::getInstance()->setModule('news')->getArticleModel();
        $request = $this->getRequest();
        $pageIndex = $request->getParam('pageIndex', 1);
        $perPage = 20;
        $offset = ($pageIndex - 1) * $perPage;

        /**
         * Build article search expression
         */
        $user = Zend_Auth::getInstance()->getIdentity();
        $params = null;
        $exp = array(
            'created_user_id' => $user->id,
        );

        /**
         * @since 2.0.8
         */
        $lang = $request->getParam('lang', Tomato_Config::getConfig()->web->lang);
        $articleModel->setLang($lang);
        $this->view->assign('pageIndex', $pageIndex);
        if ($request->isPost()) {
            $is_read = $request->getPost('is_read');
            $keyword = $request->getPost('keyword');
            $categoryId = $request->getPost('category');
            $findMineOnly = $request->getPost('findMyArticles');
            $purifier = new HTMLPurifier();

            if ($keyword) {
                $exp['keyword'] = $purifier->purify($keyword);
            }
            if ($id) {
                $exp['id'] = $purifier->purify($id);
            }
            if ($categoryId) {
                $exp['category_id'] = $categoryId;
            }
            if (null == $findMineOnly) {
                $exp['created_user_id'] = null;
            }
            if ($request->getPost('status')) {
                $exp['status'] = $request->getPost('status');
            }
            $params = rawurlencode(base64_encode(Zend_Json::encode($exp)));
        } else {
            $params = $request->getParam('q');
            if ($params != null) {
                $exp = rawurldecode(base64_decode($params));
                $exp = Zend_Json::decode($exp);
            } else {
                $params = rawurlencode(base64_encode(Zend_Json::encode($exp)));
            }
        }
        //$articles = $articleModel->getAll();
        $articles = $articleModel->find($offset, $perPage, $exp);
        $numArticles = $articleModel->count($exp);

        /**
         * Paginator
         */
        $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($articles, $numArticles));
        $paginator->setCurrentPageNumber($pageIndex);
        $paginator->setItemCountPerPage($perPage);
        $this->view->assign('exp', $exp);
        $this->view->assign('articles', $articles);
        $this->view->assign('numArticles', $numArticles);
        $this->view->assign('paginator', $paginator);
        $this->view->assign('paginatorOptions', array(
            'path' => $this->view->url(array(), 'news_article_list'),
            'itemLink' => (null == $params) ? 'page-%d/' . $request->getParam('lang') . '/' : 'page-%d/' . $request->getParam('lang') . '?q=' . $params,
        ));
    }

    /**
     * Preview article
     *
     * @since 2.0.4
     * @return void
     */
    public function previewAction() {
        $request = $this->getRequest();
        $revisionId = $request->getUserParam('revision_id');

        $conn = Tomato_Db_Connection::factory()->getMasterConnection();
        $revisionDao = Tomato_Model_Factory::getInstance()->setModule('news')->getRevisionDao();
        $revisionDao->setDbConnection($conn);
        $revision = $revisionDao->getById($revisionId);
        if (null == $revision) {
            throw new Tomato_Exception_NotFound();
        }
        $this->view->assign('revision', $revision);
    }

}
